package org.jeecg.modules.wmhb.job;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.UserConstant;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.wmhb.entity.*;
import org.jeecg.modules.wmhb.service.*;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 订货明细自动更新到货时间和采购时间
 */
@Slf4j
public class PurchaseOrderDyJob implements Job {
    @Autowired
    private IWmPurchaseOrderDetailDyService purchaseOrderDetailDyService;
    @Autowired
    private IWmTaskService wmTaskService;
    @Autowired
    private IWmTaskBomService wmTaskBomService;
    @Autowired
    private IWmTaskLogService wmTaskLogService;
    @Autowired
    private IWmTaskbookService wmTaskbookService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info(String.format(" =============PurchaseOrderDyJob============ !  时间:" + DateUtils.getTimestamp()));
        //物料有到货记录的任务ID列表
        List<String> wmTaskIdList = new ArrayList<>();
        //获取所有已核减和已采购的任务BOM
        List<WmTaskBom> wmTaskBomList = wmTaskBomService.orderBomList();
        //更新采购时间和到货时间到货数量
        for(WmTaskBom wmTaskBom: wmTaskBomList){
            List<WmPurchaseOrderDetailDy> wmPurchaseOrderDetailDyList = new ArrayList<>();
            if(!StringUtils.isEmpty(wmTaskBom.getSeriesNo())) {
                //按物料序号查询订货明细
                wmPurchaseOrderDetailDyList = purchaseOrderDetailDyService.searchBySeriesNo(wmTaskBom.getSeriesNo());
            }
            else{
                //获取没有序号的订货明细数据
                WmTask wmTask = wmTaskService.getById(wmTaskBom.getWmTaskId());
                if(wmTask == null){
                    continue;
                }
                WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
                if(wmTaskbook == null){
                    continue;
                }
                wmPurchaseOrderDetailDyList = purchaseOrderDetailDyService.queryNoSeriesNoOfTaskBom(wmTaskBom, wmTaskbook);
            }
            updatePurchaseOrArrive(wmPurchaseOrderDetailDyList, wmTaskBom);
        }
    }

    //更新到货时间和采购时间
    private void updatePurchaseOrArrive(List<WmPurchaseOrderDetailDy> wmPurchaseOrderDetailDyList, WmTaskBom wmTaskBom){
        List<String> wmTaskIdList = new ArrayList<>();
        for(WmPurchaseOrderDetailDy wmPurchaseOrderDetailDy: wmPurchaseOrderDetailDyList) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            //如果任务BOM没有记录采购时间，而订货明细有订货时间，则更新任务BOM的采购时间
            if (wmTaskBom.getPurchaseTime() == null && !StringUtils.isEmpty(wmPurchaseOrderDetailDy.getOrderDate())) {
                try {
                    Date purchaseTime = format.parse(wmPurchaseOrderDetailDy.getOrderDate());
                    wmTaskBom.setPurchaseTime(purchaseTime);
                    wmTaskBom.setStatus(UserConstant.TASKBOM_PURCHASED);
                }
                catch (ParseException e) {}
            }

            //如果任务BOM没有记录到货时间，而订货明细有订货时间，则更新任务BOM的到货时间
            if (wmTaskBom.getArriveTime() == null && !StringUtils.isEmpty(wmPurchaseOrderDetailDy.getFactArriveTime()) && !StringUtils.isEmpty(wmPurchaseOrderDetailDy.getQuantity())) {
                try {
                    Date arriveTime = format.parse(wmPurchaseOrderDetailDy.getFactArriveTime());
                    wmTaskBom.setArriveTime(arriveTime);
                    wmTaskBom.setStatus(UserConstant.TASKBOM_ARRIVED);
                    wmTaskBom.setArriveNum(Double.parseDouble(wmPurchaseOrderDetailDy.getQuantity()));
                }
                catch (ParseException e) {}

                //序号对应的任务，到货后的任务列表
                if(!wmTaskIdList.contains(wmTaskBom.getWmTaskId())) {
                    wmTaskIdList.add(wmTaskBom.getWmTaskId());
                }

                wmPurchaseOrderDetailDy.setIsCheckTaskBom(UserConstant.SYS_YES);
                purchaseOrderDetailDyService.updateById(wmPurchaseOrderDetailDy);
            }
            wmTaskBomService.updateById(wmTaskBom);
        }

        //判断任务BOM是否全部已采购和已到货
        checkIsAllPurchaseOrArrive(wmTaskIdList);
    }

    //判断任务BOM是否全部采购和到货
    private void checkIsAllPurchaseOrArrive(List<String> wmTaskIdList){
        for(String wmTaskId: wmTaskIdList){
            List<String> taskIdList = new ArrayList<>();
            taskIdList.add(wmTaskId);
            WmTask wmTask = wmTaskService.getById(wmTaskId);

            //只更新已核减已采购状态下的任务及其子任务
            List<String> statusList = new ArrayList<>();
            statusList.add(UserConstant.TASK_STATUS_ORDERED);
            statusList.add(UserConstant.TASK_STATUS_PURCHASED);
            //当前任务是否已核减或已采购
            if(statusList.contains(wmTask.getStatus())) {
                List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTask);
                //已报料任务BOM
                List<WmTaskBom> baoliaoTaskBomList = wmTaskBomService.baoliaoListByWmTaskIds(taskIdList);//待报料或已核减物料
                List<WmTaskBom> noArriveTaskBomList = wmTaskBomService.noArriveListByWmTaskId(wmTaskId); //物料未到齐
                for(WmTask wmTaskItem: wmTaskList) {
                    //报料初始状态和已核减状态物料列表为空时，说明任务的物料全部进入采购状态或之后的状态，祖先任务下面的BOM没有处于未报料和已报料的
                    if (baoliaoTaskBomList.isEmpty()) {
                        //物料已采购
                        wmTaskItem.setStatus(UserConstant.TASK_STATUS_PURCHASED);//已采购
                        //更新任务日志
                        wmTaskLogService.updateTaskLog(wmTaskItem.getId(), UserConstant.TASK_LOG_TYPE_BOM_PURCHASE);
                    }
                    //祖先任务下面的BOM没有未到货的，即全部到货了
                    if (noArriveTaskBomList.isEmpty()) {
                        //物料已到货，覆盖已采购状态
                        wmTaskItem.setStatus(UserConstant.TASK_STATUS_BOM_REACHED); //物料到货
                        //更新任务日志
                        wmTaskLogService.updateTaskLog(wmTaskItem.getId(), UserConstant.TASK_LOG_TYPE_BOM_REACHED);
                    }
                    wmTaskService.updateById(wmTaskItem);

                    //更新任务书信息
                    if(wmTaskItem.getAncestors().equals(UserConstant.ANCESTOR_ZERO)) {
                        WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
                        wmTaskbook.setProgress(wmTaskItem.getProgress());
                        wmTaskbook.setStatus(wmTaskItem.getStatus());
                        wmTaskbook.setCurrentNodeIndex(wmTaskItem.getCurrentNodeIndex());
                        wmTaskbook.setCurrentNodeId(wmTaskItem.getCurrentNodeId());
                        wmTaskbookService.updateById(wmTaskbook);
                    }
                }

                //判断同级的任务是否都已到货，有则更新父任务和任务书的当前部门信息（逻辑有更新，此部分可能废弃，因为设计起始任务和根任务已改为同一个任务）
                sameLevelTaskCheck(wmTask);
            }
        }
    }

    //如果同级别的任务都大于当前任务的当前部门序号，则更新父任务和任务书的当前部门信息
    private void sameLevelTaskCheck(WmTask wmTask){
        Boolean flag = true;
        List<WmTask> wmTaskList = wmTaskService.sameLevelTask(wmTask);
        for(WmTask wmTaskItem: wmTaskList){
            //判断同级任务是否都大于当前任务的当前部门序号
            if(wmTaskItem.getCurrentNodeIndex() < wmTask.getCurrentNodeIndex()){
                flag = false;
            }

            if(wmTaskItem.getId().equals(wmTask.getId())){
                //从数据库中获取最新的当前任务
                wmTask = wmTaskItem;
            }
        }

        if(flag){
            //更新祖先任务当前部门信息
            List<WmTask> ancestorTaskList = wmTaskService.ancestorTask(wmTask);
            if(!ancestorTaskList.isEmpty()) {
                for(WmTask wmTaskItem: ancestorTaskList) {
                    wmTaskItem.setCurrentNodeId(wmTask.getCurrentNodeId());
                    wmTaskItem.setCurrentNodeIndex(wmTask.getCurrentNodeIndex());
                    wmTaskItem.setCurrentNodeTime(new Date());
                    wmTaskItem.setProgress(wmTask.getProgress());
                    wmTaskItem.setStatus(wmTask.getStatus());
                    wmTaskService.updateById(wmTaskItem);
                }
            }

            //更新任务书当前部门信息
            WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
            wmTaskbook.setCurrentNodeId(wmTask.getCurrentNodeId());
            wmTaskbook.setCurrentNodeIndex(wmTask.getCurrentNodeIndex());
            wmTaskbook.setProgress(wmTask.getProgress());
            wmTaskbook.setStatus(wmTask.getStatus());
            wmTaskbookService.updateById(wmTaskbook);
        }
    }
}
